<template>
  <div class="plan_detail">
    <a-form :form="ruleForm" layout="inline">
    <div class="title_head">
      <a-icon @click="goBack" type="left" />
      <div class="title">运营计划名称</div>
      <a-form-item label="">
        <a-input v-decorator="['name', {rules: [{ required: true, message: '请输入计划名称' }]} ]" placeholder="请输入计划名称" />
      </a-form-item>
    </div>
    <div class="content">
      <div class="left_con">
        <a-steps direction="vertical" :current="currentStep">
          <a-step title="触发条件" description="触发条件" />
          <a-step title="目标设置" description="设置运营计划的目标" />
        </a-steps>
      </div>
      <div class="right_con">
          <div v-show="step === 'first'">
            <a-row>
            <a-form-item label="计划类型">
              <div class="plan_type_list">
                <div class="plan_type" :class="{ selected: formType === 0 }" @click="changeFormType(0)">
                  <a-icon type="thunderbolt" theme="filled" />
                  <div>触发型-完成A</div>
                  <div class="selected_icon">
                    <div class="selected_rect"></div>
                    <a-icon class="selected_check" type="check" />
                  </div>
                </div>
                <div class="plan_type" :class="{ selected: formType === 1 }" @click="changeFormType(1)">
                  <a-icon type="thunderbolt" theme="filled" />
                  <div>触发型-完成A 未完成B</div>
                  <div class="selected_icon">
                    <div class="selected_rect"></div>
                    <a-icon class="selected_check" type="check" />
                  </div>
                </div>
              </div>
            </a-form-item>
          </a-row>
            <a-form-item>
              <slot name="label">
                <div>触发时间</div>
              </slot>
              <div style="background: #f5f8fc;padding: 12px;">
                <div class="flex">
                  <a-icon v-if="expand" @click="handerExpand" class="expand" type="up-square" />
                  <a-icon v-else @click="handerExpand" class="expand" type="down-square" />
                  在计划起止时间内完成下列事件后
                  <div>
                    <a-button @click="addEvent" type="link">添加事件</a-button>
                  </div>
                </div>
                <div v-show="expand">
                  <EventRule type="edit" ref="eventRule" :projectId="projectId" />
                </div>
              </div>
              <div v-if="formType === 1" class="flex" style="margin-top: 20px;">
                  <div style="width: 30px;">且在</div>
                  <a-input-number v-model="windowTimes" style="width: 100px; margin: 0 10px;" />
                  <a-select v-model="windowUnit" style="width: 100px;margin-right: 10px;">
                    <a-select-option value="MINUTE">分钟</a-select-option>
                    <a-select-option value="HOUR">小时</a-select-option>
                    <a-select-option value="DAY">天</a-select-option>
                  </a-select>
                  <div>内</div>
              </div>
              <div style="background: #f5f8fc; margin-top: 20px;padding: 12px;" v-show="formType === 1">
                <div class="flex">
                  <a-icon v-if="expandB" @click="handerExpandB" class="expand" type="up-square" />
                  <a-icon v-else @click="handerExpandB" class="expand" type="down-square" />
                  未完成事件 B
                  <div>
                    <a-button @click="addEventB" type="link">添加事件</a-button>
                  </div>
                </div>
                <div v-show="expandB">
                  <EventRuleB type="edit" ref="eventRuleB" :projectId="projectId" />
                </div>
              </div>
            </a-form-item>
            <div class="delay-row">
              <div>则</div>
              <a-form-item class="delay_input" label="">
                <a-select v-model="isdelay">
                  <a-select-option :value="0">立即</a-select-option>
                  <a-select-option :value="1">延迟</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item class="delay_input" v-if="isdelay===1" label="">
                <a-input-number v-model="delayTimes" />
              </a-form-item>
              <a-form-item class="delay_input" v-if="isdelay===1" label="">
                <a-select v-model="delayUnit">
                  <a-select-option value="MINUTE">分钟</a-select-option>
                  <a-select-option value="HOUR">小时</a-select-option>
                  <a-select-option value="DAY">天</a-select-option>
                </a-select>
              </a-form-item>
              对受众用户进行触达
            </div>
            <a-form-item label="起止时间" style="width: 100%;">
              <a-range-picker
                :show-time="{ format: 'HH:mm' }"
                format="YYYY-MM-DD HH:mm"
                :placeholder="['开始时间', '结束时间']"
                v-decorator="['scheduleDate', {rules: [{ required: true, message: '请选择起止时间' }]} ]"
              />
            </a-form-item>
            <a-form-item label="参与限制">
              <a-radio-group @change="changeTime" v-decorator="['limit',  {rules: [{ required: true, message: '请选择参与限制' }], initialValue: 0} ]">
                <a-radio :value="0">参与1次</a-radio>
                <a-radio :value="1">参与多次</a-radio>
              </a-radio-group>
            </a-form-item>
            <div v-if="times === 1">
              <a-form-item label="">
                同一个用户
                <a-input-number v-model="limitDay" />
                自然日内，最多参与
                <a-input-number v-model="limitTimes" />
                次
              </a-form-item>
            </div>
            <div v-if="times === 1">
              提示：当用户退出计划后，才可再次进入，点击查看<a href="">运营计划退出机制</a>
            </div>
            <div v-else>
              当前计划，同一用户仅参与 1 次
            </div>
          </div>
          <div v-show="step === 'second'">
            <Target type="edit" ref="target" :projectId="projectId" />
            <a-button @click="addTarget" type="primary"><a-icon type="plus" />添加次要目标</a-button>
          </div>
      </div>
    </div>
  </a-form>
  <div class="save_row">
    <a-space>
      <a-button v-if="step === 'second'" @click="step = 'first'">上一步</a-button>
      <a-button v-if="step === 'first'" type="primary" @click="nextStep">下一步</a-button>
      <a-button type="primary" @click="onSubmit">保存</a-button>
    </a-space>
  </div>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'
import { baseMixin } from '@/store/app-mixin';
import EventRule from "./eventRule.vue";
import EventRuleB from "./eventRuleB.vue";
import Target from "./target.vue";
import moment from 'moment';

  export default {
    name: 'PlanList',
    mixins: [baseMixin],
    components: {
      EventRule,
      EventRuleB,
      Target
    },
    beforeCreate() {
      this.ruleForm = this.$form.createForm(this, { });
    },
    data () {
      return {
        properties: [],
        delayTimes: 15,
        delayUnit: 'MINUTE',
        windowTimes: 15,
        windowUnit: 'MINUTE',
        formType: 0,
        expand: true,
        expandB: true,
        form: {
          statusBtn: false,
          loadingBtn: false,
          data: {
            permissionIds: []
          }
        },
        step: 'first',
        autoExpandParent: true,
        projectId: '',
        eventList: [],
        times: 0,
        isdelay: 0,
        limitDay: 15,
        limitTimes: 1
      }
    },
    created() {
      this.projectId = this.$route.query.projectId;
    },
    computed: {
      currentStep() {
        return this.step === 'first' ? 0 : 1;
      }
    },
    mounted () {
      this.onLoadPlanConfig();
    },
    methods: {
      ...mapActions('planManage', ['getAllPlanList', 'addPlan', 'getPlan']),
      ...mapActions('projectManage', ['getProjectList', 'getEventList', 'getUserProperties']),
      addEvent () {
        this.$refs.eventRule.addEvent();
      },
      addEventB () {
        this.$refs.eventRuleB.addEvent();
      },
      handerExpand() {
        this.expand = !this.expand;
      },
      handerExpandB() {
        this.expandB = !this.expandB;
      },
      changeFormType(type) {
        this.formType = type;
      },
      changeTime(e) {
        this.times = e.target.value;
      },
      goBack() {
        this.$router.history.go(-1);
      },
      // 保存
      onSubmit () {
        this.ruleForm.validateFieldsAndScroll((errors, values) => {
          if (errors) {
            this.step = 'first';
            return;
          }

          if (!this.$refs.eventRule.validate()) {
            this.step = 'first';
            return;
          }

          if (this.formType === 1 && !this.$refs.eventRuleB.validate()) {
            this.step = 'first';
            return;
          }

          if (!this.$refs.target.validate()) {
            this.step = 'second';
            return;
          }
          const saveData = {
            name: values.name, // 计划名称
            type: this.formType, // 类型
            scheduleStart: values.scheduleDate[0].format('YYYY-MM-DD hh:mm:ss'), //开始时间
            scheduleEnd: values.scheduleDate[1].format('YYYY-MM-DD hh:mm:ss'), //结束时间
            sendRule: JSON.stringify({
              limit: 1,
              value: 15,
              unit: 'HOUR'
            }),
            convertRule: JSON.stringify({}),
          };

          const delay_config = {
            value: this.isdelay === 0 ? 0 : this.delayTimes,
            unit: this.delayUnit,
          };
          if (this.formType === 0) {
            const pattern_first_do = this.$refs.eventRule.getRuleData();
            saveData.triggerRule = JSON.stringify({
              pattern_first_do,
              delay_config
            });
          } else {
            const pattern_first_do = this.$refs.eventRule.getRuleData();
            const json = this.$refs.eventRuleB.getRuleData();
            const pattern_then_not_do = { ...json, window: { value: this.windowTimes, unit: this.windowTimes }};
            saveData.triggerRule = JSON.stringify({
              pattern_first_do,
              pattern_then_not_do,
              delay_config
            });
          }

          const convertRule = this.$refs.target.getRuleData();
          saveData.convertRule = JSON.stringify(convertRule);

          if (values.limit) {
            // 参与多次
            saveData.joinLimitRule = JSON.stringify({
                limit: this.limitTimes,
                value: this.limitDay,
                unit: 'DAY'
            });
            this.times = 1;
          } else {
            // 参与1次
            saveData.joinLimitRule = JSON.stringify({});
          }

          saveData.projectId = this.projectId;
          saveData.id = this.$route.query.id;
          this.addPlan(saveData).then(res => {
            if (res.code === 0) {
              this.$router.push('/operationPlanManage');
            } else {
              this.$message.warning('保存失败');
            }
          }, (err) => {
            this.$message.warning(err.msg);
          });
        });
      },
      addTarget () {
        this.$refs.target.addTarget();
      },
      nextStep() {
        this.step = 'second';
      },
      // 初始化加载页面数据
      onLoadPlanConfig () {
        if (this.$route.name === 'OperationPlanManageEdit') {
          this.getPlan(this.$route.query).then(res => {
            if (res.code === 0) {
              const { name, scheduleStart, scheduleEnd, joinLimitRule, type, convertRule, triggerRule } = res.data;
              const scheduleDate = [moment(scheduleStart), moment(scheduleEnd)];
              this.formType = type;
              if (joinLimitRule !== '{}') {
                const joinLimitRuleObj = JSON.parse(joinLimitRule);
                this.limitTimes = joinLimitRuleObj.limit;
                this.limitDay = joinLimitRuleObj.value;
                this.times = 1;
              }
              this.ruleForm.setFieldsValue({
                name,
                scheduleDate,
                limit: joinLimitRule === '{}' ? 0: 1
              });

              const triggerRuleObj = JSON.parse(triggerRule);
              const { delay_config, pattern_first_do, pattern_then_not_do } = triggerRuleObj;
              if (delay_config.value) {
                this.isdelay = 1;
                this.delayTimes = delay_config.value;
                this.delayUnit = delay_config.unit;
              }

              if (this.formType === 1) {
                this.$refs.eventRule.setRuleData(pattern_first_do);
                this.$refs.eventRuleB.setRuleData(pattern_then_not_do);
              } else {
                this.$refs.eventRule.setRuleData(pattern_first_do);
              }

              const convertRuleObj = JSON.parse(convertRule);

              this.$refs.target.setRuleData(convertRuleObj);
            }
          });
        }
        this.getEventList(this.projectId).then(res => {
          this.eventList = [...this.properties, ...res];
        });
        this.getUserProperties(this.projectId).then(res => {
          this.properties = [...this.properties, ...res];
        });
      }
    }
  }
</script>

<style scoped>

.plan_detail {
  padding: 16px;
  background: #fff;
  width: 100%;
}
  .title_head {
    display: flex;
    align-items: center;
  }

  .title {
    line-height: 32px;
    margin: 0 12px;
    color: #4079fb;
    border-radius: 3px;
    background-color: #e2ebff;
    height: 32px;
    padding: 0 16px;
  }

  .content {
    display: flex;
    margin-top: 20px;
  }

  .plan_type_list {
    display: flex;
  }

  .plan_type_list .anticon-thunderbolt{
    margin-top: 14px;
  }

  .plan_type {
    display: flex;
    border: 1px solid #999;
    border-radius: 4px;
    margin-right: 16px;
    padding: 0 30px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .plan_type.selected {
    color: #01bf8a;
    border-color: #01bf8a;
  }

  .selected_icon {
    position: absolute;
    display: none;
    right: 0;
    top: 0;
    color: #fff;
    height: 20px;
    line-height: 20px;
  }

  .selected_rect {
    background-color: #01bf8a;
    width: 40px;
    height: 20px;
    transform: rotate(30deg);
    position: absolute;
    right: -10px;
    top: -8px;
  }

  .selected_check {
    line-height: 20px;
    font-size: 12px;
    position: absolute;
    right: 0;
    top: 0;
  }

  .selected .selected_icon {
    display: block;
  }

  .left_con {
    width: 240px;
    box-shadow: 0 0 5px rgba(153,170,192,.17);
    padding: 16px;
  }

  .right_con {
    flex: 1;
    margin-left: 20px;
    box-shadow: 0 0 5px rgba(153,170,192,.17);
    padding: 16px;
    overflow: auto;
    max-height: calc(100vh - 380px);
  }

  .expand {
    cursor: pointer;
    margin-right: 5px;
  }

  .delay-row {
    display: flex;
    line-height: 40px;
  }

  .delay_input {
    margin: 0 5px;
  }

  .save_row {
    position: absolute;
    bottom: 0;
    background: #fff;
    /* height: 60px; */
    padding: 20px;
    left: 0;
    right: 0;
  }

  .flex {
    display: flex;
    align-items: center;
  }
</style>